package cz.muni.fi.pa165.bookingmanager.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.util.JdbcUtils;

/**
 *
 * @author Jiří Holuša
 */
public class RoleSecurityJdbcRealm extends JdbcRealm {
    
    
    
    public RoleSecurityJdbcRealm() {		
        super();

        //get the DataSource that JSecurity's JdbcRealm
        //should use to find the user's password
        //using the provided username
        //see context.xml for this DataSource's properties
        InitialContext ic;
        DataSource ds;

        try {
            ic = new InitialContext();
            ds = (DataSource) ic.lookup("jdbc/dynamicDB");
            this.setDataSource(ds);
            SecurityManager securityManager = new DefaultSecurityManager(this);
            
            SecurityUtils.setSecurityManager(securityManager);
            
            
        } catch (NamingException e) {
            e.printStackTrace();
        }
        
        
            
        
        }
    
        @Override
        protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException { 
        PreparedStatement ps = null;  
        ResultSet rs = null;  
        Set roleNames = new LinkedHashSet();  
  
        try {  
            ps = conn.prepareStatement(userRolesQuery);  
            ps.setString(1, username);  
          
  
            // Execute query  
            rs = ps.executeQuery();  
  
            // Loop over results and add each returned role to a set  
            while (rs.next()) {  
  
                String roleName = rs.getString(1).toLowerCase();  
  
                // Add the role to the list of names if it isn't null  
                if (roleName != null) {  
                    roleNames.add(roleName);  
                } 
                  
            }  
        } finally {  
            JdbcUtils.closeResultSet(rs);  
            JdbcUtils.closeStatement(ps);  
        }  
  
        return roleNames;  
    }       
            
        
    
 

}
